<template>
	<view class="add-product">
		<view class="add-product-1">
			<view class="add-image" @click="choseMainImg" v-if="!caseInfo.image_middle">
				<view>
					<image src="https://master.shengejiaju.cn/web/static/icons/ico_add_pic02@2x.png"></image>
					<view>上传主图</view>
				</view>
			</view>
			<view class="show-img" v-else>
				<image :src="caseInfo.image_middle" @click="previewImg" mode="aspectFill"></image>
				<view @click="choseMainImg">更换商品主图</view>
			</view>
		</view>
		<view class="add-product-2">
			<view class="add-product-2-cell">
				<text class="title">标题</text>
				<input v-model="caseInfo.case_name" />
			</view>
			<view class="add-product-2-cell">
				<text class="title">简介</text>
				<input v-model="caseInfo.brief" />
			</view>
			<view class="add-product-2-cell">
				<text class="title">平方数</text>
				<input v-model="caseInfo.square"/>
			</view>
			<view class="add-product-2-cell">
				<text class="title">空间类型</text>
				<picker @change="pickerSpace" :value="selectSpaceCurrent" :range="spaceList" class="picker">
					<view class="readonly">{{placeholder}} <image src="https://master.shengejiaju.cn/web/static/icons/ico_more_goods@2x.png"></image></view>
				</picker>
			</view>
			<view class="add-product-2-cell">
				<text class="title">风格</text>
				<picker @change="pickerStyle" :value="selectStyleCurrent" :range="classList" range-key="style_name" class="picker">
					<view class="readonly">{{placeholder1}}<image src="https://master.shengejiaju.cn/web/static/icons/ico_more_goods@2x.png"></image></view>
				</picker>
			</view>
			<view class="add-product-2-cell">
				<text class="title" style="width: 3em;">排序</text>
				<input type="number"  v-model="caseInfo.sort" placeholder="数字越大，排序越靠前(默认为0)" placeholder-style="color:#FE9B26"/>
			</view>
		</view>
		
		<view class="add-product-5">
			<text class="title">案例商品 <text>（可选）</text></text>
			<view class="radioChange">
				<radio-group @change="radioChange">
					<label class="radio">
						<radio value="1" :checked="caseInfo.goods_type==1?true:false" :disabled="caseInfo.case_id?true:false" color="#2073F5"/>平台商品
					</label>
					<label class="radio">
						<radio value="2" :checked="caseInfo.goods_type==2?true:false" :disabled="caseInfo.case_id?true:false" color="#2073F5"/>自营商品
					</label>
				</radio-group>
			</view>
			<view class="piclist-box">
				<view class="showimg" v-for="(data,index) in caseProlist" :key="index" v-if="caseProlist.length">
					<image class="close" src="https://master.shengejiaju.cn/web/static/icons/ico_close@2x_white.png" @click="delCase(index,data.id)"></image>
					<image class="pic" :src="data.image" @click="previewCaseImg(index)"></image>
					<view class="piclist-box-tit">{{data.title}}</view>
				</view>
				<view @click="selectProItem"><image src="https://master.shengejiaju.cn/web/static/icons/ico_ad_pic02.png"></image></view>
			</view>
		</view>
		
		<view class="add-product-5">
			<text class="title">案例副图</text>
			<view class="piclist-box">
				<view class="showimg" v-for="(data,index) in viceImages" :key="index" v-if="viceImages.length">
					<image class="close" src="https://master.shengejiaju.cn/web/static/icons/ico_close@2x_white.png" @click="delVice(data.id,index)"></image>
					<image class="pic" :src="data.url" mode="aspectFit" @click="previewViceImg(index)"></image>
				</view>
				<view @click="addVice"><image src="https://master.shengejiaju.cn/web/static/icons/ico_ad_pic02.png"></image></view>
			</view>
		</view>
		
		<view class="add-product-5">
			<text class="title">案例详情图</text>
			<view class="piclist-box">
				<view class="showimg" v-for="(data,index) in infoImages" :key="index" v-if="infoImages.length">
					<image class="close" src="https://master.shengejiaju.cn/web/static/icons/ico_close@2x_white.png" @click="delInfo(data.id,index)"></image>
					<image class="pic" :src="data.url" mode="aspectFit" @click="previewInfoImg(index)"></image>
				</view>
				<view @click="addInfo"><image src="https://master.shengejiaju.cn/web/static/icons/ico_ad_pic02.png"></image></view>
			</view>
		</view>
		
		<view class="add-product-6">
			<text class="title">添加视频</text>
			<view class="video-box">
				<view class="video-show" v-if="caseInfo.video">
					<video :src="caseInfo.video"></video>
				</view>
				<view class="change-video" v-if="caseInfo.video"  @click="addVideo">更换视频</view>
				<view class="video-add" @click="addVideo" v-else>
					<view><image src="https://master.shengejiaju.cn/web/static/icons/ico_ad_vedio@2x.png"></image></view>
					<view>点击添加</view>
				</view>
				<progress :percent="percent" show-info stroke-width="3" v-if="is_uploading" />
			</view>
		</view>
		
		<view class="add-product-submit">
			<button @click="submit">保存</button>
		</view>
		
		<uni-popup ref="selectPro" type="bottom" class="selectProItem">
			<view class="search-bar">
				<uni-search-bar @confirm="search" @input="input" :radius="100" cancelButton="always" @cancel="cancel"></uni-search-bar>
			</view>
			<scroll-view scroll-y class="selectView" @scrolltolower="loadMore">
				<block v-if="ProList.length">
					<checkbox-group v-model="choseList" @change="change">
						<view class="proList-item" v-for="(data,index) in ProList" :key="data.goods_id">
							<label>
								<!-- #ifdef MP-WEIXIN -->
								<checkbox :value="caseInfo.goods_type==2?data.store_goods_id:data.goods_id" :checked="data.checked" color="#FFFFFF" />
								<!-- #endif -->
								<!-- #ifdef H5 || APP-PLUS -->
								<checkbox :value="caseInfo.goods_type==2?(data.store_goods_id).toString():(data.goods_id).toString()" :checked="data.checked" color="#FFFFFF"/>
								<!-- #endif -->
								<image :src="data.image_middle"></image>
								<view class="proList-item-info">
									<view class="proList-item-info-tit">{{caseInfo.goods_type==2?data.store_goods_name:data.goods_name}}</view>
									<view class="proList-item-info-des">{{caseInfo.goods_type==2?data.store_goods_sn:data.goods_sn}}</view>
								</view>
							</label>
						</view>
					</checkbox-group>
				</block>
				<nothing :text="'没有商品'" :btn="false" v-else></nothing>
				<no-more :text="'数据加载完毕'" v-if="ProList.length && noMore"></no-more>
			</scroll-view>
			<view class="confirm-bar"><text @click="sure">确认选择</text></view>
		</uni-popup>
		
	</view>
</template>

<script>
	const md5 = require('../../static/utils/md5')
	import host from '@/api/config.js'
	export default {
		data() {
			return {
				selectSpaceCurrent: 0,
				selectStyleCurrent: 0,
				placeholder: '请选择空间类型',
				placeholder1: '请选择风格',
				classList: [],
				spaceList: [],
				caseProlist: [],
				viceImages: [],
				infoImages: [],
				caseInfo: {
					image: '',
					image_middle: '',
					image_thumb: '',
					case_name: '',
					brief: '',
					square: '',
					space: '',
					style_id: '',
					sort: '',
					user_id: JSON.parse(uni.getStorageSync('userInfo')).user_id,
					store_id: JSON.parse(uni.getStorageSync('userInfo')).store_id,
					type: 1,
					video: '',
					case_goods: '',
					viceImages: '',
					infoImages: '',
					goods_type: 1
				},
				uploadParameter: {},
				is_uploading: false,
				percent: 0,
				ProList: [],
				searchValue: '',
				choseList: [],
				page: 0,
				noMore: false
			};
		},
		onLoad(options) {
			if(options.case_id){
				uni.setNavigationBarTitle({
					title: '编辑案例'
				})
				this.getCaseInfo(options.case_id)
			}
			this.init()
		},
		methods: {
			// 获取案例详情
			getCaseInfo(id){
				this.$api.CaseInfo({case_id: id}).then(res => {
					let caseInfo = res.datas
					if(caseInfo.space){
						this.spaceList.forEach((item,index) => {
							if(caseInfo.space===item){
								this.selectSpaceCurrent = index
								this.placeholder = item
							}
						})
					}
					if(caseInfo.style_id){
						this.classList.forEach((item,index) => {
							if(caseInfo.style_id == item.style_id){
								this.placeholder1 = caseInfo.style_name
								this.selectStyleCurrent = index
							}
						})
					}
					if(caseInfo.vice_big_list){
						caseInfo.vice_big_list.forEach((item,index) => {
							this.viceImages.push({
								id: item.case_image_id,
								url: item.image
							})
						})
					}
					if(caseInfo.img_info_list){
						caseInfo.img_info_list.forEach((item,index) => {
							this.infoImages.push({
								id: item.case_image_id,
								url: item.image
							})
						})
					}
					if(caseInfo.case_goods){
						caseInfo.case_goods.forEach((item,index) => {
							this.caseProlist.push({
								id: item.store_goods_id,
								image: item.image_middle,
								title: item.store_goods_name
							})
						})
					}
					this.caseInfo = {
						case_id: caseInfo.case_id,
						image: caseInfo.image,
						image_middle: caseInfo.image_middle,
						image_thumb: caseInfo.image_thumb,
						case_name: caseInfo.case_name,
						brief: caseInfo.brief,
						square: caseInfo.square,
						space: caseInfo.space,
						style_id: caseInfo.style_id,
						sort: caseInfo.sort,
						user_id: caseInfo.user_id,
						store_id: caseInfo.store_id,
						type: 1,
						video: caseInfo.video,
						goods_type: caseInfo.goods_type
					}
				})
			},
			// 参数排序
			objKeySort(obj) {
				var newkey = Object.keys(obj).sort();
				var newObj = {};
				for (var i = 0; i < newkey.length; i++) {
						newObj[newkey[i]] = obj[newkey[i]];
				}
				return newObj;
			},
			init(){
				let data = {}
				// #ifdef H5
				let ua = navigator.userAgent.toLowerCase()
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					data.port = 'wechat'
				}else{
					data.port = 'h5'
				}
				// #endif
				
				// #ifdef APP-PLUS
				switch(uni.getSystemInfoSync().platform){
					case 'android':
						data.port = 'android'
					  break;
					case 'ios':
						data.port = 'ios'
					  break;
				}
				// #endif
				
				data.key = JSON.parse(uni.getStorageSync('userInfo')).token
				
				data.timestamp = Math.round(new Date() * 1000)
				// 获取签名开始
				let obj = 'jjds2020+'
				let newObj = this.objKeySort(data)
				for (let i in newObj){
					obj += i + '=' + newObj[i] +'&'
				}
				obj = obj.substring(0, obj.length - 1)
				obj += '+jjds2020'
				obj = md5.hexMD5(obj)
				obj = obj.toUpperCase()
				// 获取签名结束
				data.sign = obj
				this.uploadParameter = data
				this.$api.CaseClassJson().then(res => {
					this.classList = res.datas
				})
				this.$api.CaseSpaceJson().then(res => {
					this.spaceList = res.datas
				})
			},
			// 上传商品主图
			choseMainImg(){
				let _this = this
				uni.chooseImage({
					count: 1,
					sourceType: ['album','camera'],
					success(res) {
						let imgs = []
						res.tempFiles.forEach(item => {
							imgs.push({
								uri: item.path
							})
						})
						uni.uploadFile({
							url: `${host}/api/Upimg/UpMajorImg`,
							filePath: imgs[0].uri,
							name: 'file',
							formData: {
								port: _this.uploadParameter.port,
								key: _this.uploadParameter.key,
								timestamp: _this.uploadParameter.timestamp,
								sign: _this.uploadParameter.sign
							},
							success: (uploadFileRes) => {
								_this.caseInfo.image = JSON.parse(uploadFileRes.data).datas[0].major_img_big
								_this.caseInfo.image_middle = JSON.parse(uploadFileRes.data).datas[0].major_img_middle
								_this.caseInfo.image_thumb = JSON.parse(uploadFileRes.data).datas[0].major_img_thumb
							}
						});
					}
				})
			},
			// 主图预览
			previewImg(){
				let arr = []
				arr.push(this.caseInfo.image)
				uni.previewImage({
					urls: arr
				})
			},
			// 选择空间
			pickerSpace(e){
				this.selectSpaceCurrent = e.detail.value
				this.placeholder = this.spaceList[this.selectSpaceCurrent]
				this.caseInfo.space = this.spaceList[this.selectSpaceCurrent]
			},
			// 选择风格
			pickerStyle(e){
				this.selectStyleCurrent = e.detail.value
				this.placeholder1 = this.classList[this.selectStyleCurrent].style_name
				this.caseInfo.style_id = this.classList[this.selectStyleCurrent].style_id
			},
			// 上传案例附图
			addVice(){
				let _this = this
				uni.chooseImage({
					count: 9,
					sourceType: ['album','camera'],
					success(res) {
						let url = ''
						let formData = {}
						if(_this.caseInfo.case_id){
							url = `${host}/api/Example/AddCaseImg`
							formData = {
								type: 1,
								port: _this.uploadParameter.port,
								key: _this.uploadParameter.key,
								timestamp: _this.uploadParameter.timestamp,
								sign: _this.uploadParameter.sign,
								case_id: _this.caseInfo.case_id
							}
						}else{
							url = `${host}/api/Upimg/UpViceImg`
							formData = {
								port: _this.uploadParameter.port,
								key: _this.uploadParameter.key,
								timestamp: _this.uploadParameter.timestamp,
								sign: _this.uploadParameter.sign,
							}
						}
						res.tempFilePaths.forEach((item,index) => {
							uni.uploadFile({
								url: url,
								filePath: item,
								name: 'file',
								formData: formData,
								success: (uploadFileRes) => {
									if(_this.caseInfo.case_id){
										_this.viceImages.push({
											id: JSON.parse(uploadFileRes.data).datas[0].image_id,
											url: JSON.parse(uploadFileRes.data).datas[0].imgUrl
										})
									}else{
										_this.viceImages.push({
											id: index,
											url: JSON.parse(uploadFileRes.data).datas[0].vice_img_big
										})
									}
								}
							});
						})
					}
				})
			},
			// 移除案例附图
			delVice(id,index){
				this.viceImages.splice(index,1)
				if(this.caseInfo.case_id){
					this.$api.DelCaseImg({case_image_id: id}).then(res => {
						uni.showToast({
							icon: 'none',
							title: '删除成功',
							duration: 1500
						})
					})
				}
			},
			// 上传案例详情图
			addInfo(){
				let _this = this
				uni.chooseImage({
					count: 9,
					sourceType: ['album','camera'],
					success(res) {
						let url = ''
						let formData = {}
						if(_this.caseInfo.case_id){
							url = `${host}/api/Example/AddCaseImg`
							formData = {
								type: 3,
								port: _this.uploadParameter.port,
								key: _this.uploadParameter.key,
								timestamp: _this.uploadParameter.timestamp,
								sign: _this.uploadParameter.sign,
								case_id: _this.caseInfo.case_id
							}
						}else{
							url = `${host}/api/Upimg/UpInfoImg`
							formData = {
								port: _this.uploadParameter.port,
								key: _this.uploadParameter.key,
								timestamp: _this.uploadParameter.timestamp,
								sign: _this.uploadParameter.sign,
							}
						}
						res.tempFilePaths.forEach((item,index) => {
							uni.uploadFile({
								url: url,
								filePath: item,
								name: 'file',
								formData: formData,
								success: (uploadFileRes) => {
									if(_this.caseInfo.case_id){
										_this.infoImages.push({
											id: JSON.parse(uploadFileRes.data).datas[0].image_id,
											url: JSON.parse(uploadFileRes.data).datas[0].imgUrl
										})
									}else{
										_this.infoImages.push({
											id: index,
											url: JSON.parse(uploadFileRes.data).datas[0]
										})
									}
								}
							});
						})
					}
				})
			},
			// 移除案例详情图
			delInfo(id,index){
				this.infoImages.splice(index,1)
				if(this.caseInfo.case_id){
					this.$api.DelCaseImg({case_image_id: id}).then(res => {
						uni.showToast({
							icon: 'none',
							title: '删除成功',
							duration: 1500
						})
					})
				}
			},
			// 附图预览
			previewViceImg(index){
				let arr = []
				this.viceImages.forEach(item => {
					arr.push(item.url)
				})
				uni.previewImage({
					current: index,
					urls: arr
				})
			},
			// 详情图预览
			previewInfoImg(index){
				let arr = []
				this.infoImages.forEach(item => {
					arr.push(item.url)
				})
				uni.previewImage({
					current: index,
					urls: arr
				})
			},
			// 添加视频
			addVideo(){
				let _this = this
				uni.chooseVideo({
					sourceType: ['camera', 'album'],
					success: function (res) {
						_this.is_uploading = true
						let uploadTask = uni.uploadFile({
							url: `${host}/api/Upimg/UpVideo`,
							filePath: res.tempFilePath,
							name: 'file',
							formData: {
								port: _this.uploadParameter.port,
								key: _this.uploadParameter.key,
								timestamp: _this.uploadParameter.timestamp,
								sign: _this.uploadParameter.sign
							},
							success: (uploadFileRes) => {
								if(uploadFileRes.data){
									_this.is_uploading = false
									_this.caseInfo.video = JSON.parse(uploadFileRes.data).datas
								}
							}
						});
						uploadTask.onProgressUpdate((uploadPress) => {
							_this.percent = uploadPress.progress
						})
					}
				});
			},
			// 获取商品列表
			getProList(page,keyword){
				if(this.caseInfo.goods_type==1){
					let data = {
						limit: 20,
						page: page?page:0,
						order_by: 'add_time',
						asc: 1,
						store_id: JSON.parse(uni.getStorageSync('userInfo')).store_id,
						keyword: keyword?keyword:''
					}
					this.$api.CaseGoodsList(data).then(res => {
						if(res.datas.length){
							res.datas.forEach(item => {
								this.ProList.push(item)
							})
						}else{
							this.noMore = true
						}
					})
				}else{
					let data = {
						limit: 20,
						page: page?page:0,
						order_by: 'add_time',
						asc: 1,
						store_id: JSON.parse(uni.getStorageSync('userInfo')).store_id,
						keyword: keyword?keyword:''
					}
					this.$api.StoreGoodsList(data).then(res => {
						if(res.datas.length){
							res.datas.forEach(item => {
								this.ProList.push(item)
							})
						}else{
							this.noMore = true
						}
					})
					console.log(this.ProList,'123123')
				}
			},
			loadMore(){
				if(!this.noMore){
					this.page++
					this.getProList(this.page,this.searchValue)
				}
			},
			// 选择案例关联商品
			selectProItem(){
				this.$refs.selectPro.open()
				this.searchValue = ''
				this.ProList = []
				this.getProList()
			},
			// 预览案例商品图片
			previewCaseImg(index){
				let arr = []
				this.caseProlist.forEach(item => {
					arr.push(item.image)
				})
				uni.previewImage({
					current: index,
					urls: arr
				})
			},
			// 移除案例商品
			delCase(index,id){
				this.caseProlist.splice(index,1)
				if(this.caseInfo.case_id){
					this.$api.DelateCaseGoods({case_id: this.caseInfo.case_id,goods_id: id}).then(res => {
						uni.showToast({
							icon: 'none',
							title: '移除成功',
							duration: 1500
						})
					})
				}
			},
			// 搜索商品
			search(e){
				this.ProList = []
				this.getProList(0,e.value)
			},
			// 输入事件
			input(e){
				this.searchValue = e.value
			},
			// 取消搜索
			cancel(){
				this.$refs.selectPro.close()
			},
			change(e){
				let _this = this
				var items = this.ProList,
						values = e.detail.value;
				if(this.caseInfo.goods_type==1){
					for (var i = 0, lenI = items.length; i < lenI; ++i) {
						const item = items[i]
						if(values.includes(item.goods_id.toString())){
							this.$set(item,'checked',true)
						}else{
							this.$set(item,'checked',false)
						}
					}
				}else{
					for (var i = 0, lenI = items.length; i < lenI; ++i) {
						const item = items[i]
						if(values.includes(item.store_goods_id.toString())){
							this.$set(item,'checked',true)
						}else{
							this.$set(item,'checked',false)
						}
					}
				}
			},
			sure(){
				let checked = 0
				this.ProList.forEach((item,index) => {
					if(item.checked){
						checked++
						if(this.caseInfo.goods_type==1){
							this.caseProlist.push({
								id: item.goods_id,
								image: item.image_middle,
								title: item.goods_name
							})
						}else{
							this.caseProlist.push({
								id: item.store_goods_id,
								image: item.image_middle,
								title: item.store_goods_name
							})
						}
					}
				})
				if(checked < 1){
					uni.showToast({
						icon: 'none',
						title: '请选择至少一个商品'
					})
				}else{
					this.$refs.selectPro.close()
					if(this.caseInfo.case_id){
						let caseArr = []
						this.caseProlist.forEach(item => {
							caseArr.push(item.id)
						})
						this.$api.AddCaseGoods({case_id: this.caseInfo.case_id,case_goods: caseArr.join(',')}).then(res => {
							uni.showToast({
								icon: 'none',
								title: '添加成功',
								duration: 1500
							})
						})
					}
				}
			},
			// 选择平台商品还是自营商品
			radioChange(e){
				this.caseInfo.goods_type = e.detail.value
				this.caseProlist = []
				this.ProList = []
			},
			submit(){
				let viceArr = []
				this.viceImages.forEach(item => {
					viceArr.push(item.url)
				})
				this.caseInfo.viceImages = viceArr.join(',')
				let infoArr = []
				this.infoImages.forEach(item => {
					infoArr.push(item.url)
				})
				this.caseInfo.infoImages = infoArr.join(',')
				let caseArr = []
				this.caseProlist.forEach(item => {
					caseArr.push(item.id)
				})
				this.caseInfo.case_goods = caseArr.join(',')
				if(this.caseInfo.case_id){
					delete this.caseInfo.case_goods
					delete this.caseInfo.viceImages
					delete this.caseInfo.infoImages
					this.$api.UpCase(this.caseInfo).then(res => {
						uni.showToast({
							icon: 'none',
							title: '修改成功',
							duration: 1500
						})
						setTimeout(() => {
							uni.navigateBack()
						},1500)
					})
				}else{
					this.$api.AddCase(this.caseInfo).then(res => {
						uni.showToast({
							icon: 'none',
							title: '添加成功',
							duration: 1500
						})
						setTimeout(() => {
							uni.navigateBack()
						},1500)
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	@import  '../../static/scss/add-product.scss';
	.search-bar{
		border-top: solid 1px #EEE;
		border-bottom: solid 1px #EEE;
	}
	.confirm-bar{
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		border-top: solid 1px #EEE;
		text-align: center;
		padding: 20rpx 0;
		text{
			display: inline-block;
			vertical-align: top;
			height: 50rpx;
			line-height: 50rpx;
			border-radius: 100rpx;
			font-size: 24rpx;
			background-color: #FE9B26;
			color: #FFF;
			padding: 0 30rpx;
		}
	}
	.selectView{
		position: absolute;
		top: 110rpx;
		bottom: 90rpx;
		.proList-item{
			padding: 20rpx;
			border-bottom: solid 1px #EEE;
			label{
				display: flex;
				align-items: center;
			}
			&:last-child{
				border-bottom: none;
			}
			image{
				width: 300rpx;
				height: 200rpx;
			}
			.proList-item-info{
				flex: 1;
				min-width: 0;
				margin-left: 20rpx;
				.proList-item-info-tit{
					font-size: 28rpx;
				}
				.proList-item-info-des{
					color: #666;
					margin-top: 20rpx;
				}
			}
		}
	}
	.radioChange{
		margin-bottom: 30rpx;
		font-size: 24rpx;
		label{
			margin-right: 20rpx;
		}
	}
</style>